import java.io.*;

/**
 * @author : cww
 * @date : 2020/12/27 20:21
 */
public class Sheep implements Cloneable, Serializable {

//    public Sheep(){
//
//    }
    public Sheep(String name, Integer age,Sheep goodFriend) {
        this.name = name;
        this.age = age;
        this.goodFriend = goodFriend;
    }
    private String name;
    private Integer age;
    private Sheep goodFriend;
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public Sheep getGoodFriend() {
        return goodFriend;
    }

    public void setGoodFriend(Sheep goodFriend) {
        this.goodFriend = goodFriend;
    }
    /**
     * 使用自带的克隆方法，只能实现浅克隆
     * @return
     * @throws CloneNotSupportedException
     */
//    @Override
//    protected Object clone() throws CloneNotSupportedException {
//        return super.clone();
//    }
    /**
     * 修改clone方法，实现深克隆
     * @return
     * @throws CloneNotSupportedException
     */

    @Override
    protected Object clone() throws CloneNotSupportedException {
        Object sheep = super.clone();
        Sheep newSheep = (Sheep) sheep;
        if(this.goodFriend!=null) {
            newSheep.goodFriend = (Sheep) this.goodFriend.clone();
        }
        return newSheep;
    }

    /**
     * 使用序列化的方式，实现深克隆
     * @return
     */
    public Sheep deepClone(){
        ByteArrayOutputStream outputStream;
        ObjectOutputStream objectOutputStream;
        ByteArrayInputStream inputStream;
        ObjectInputStream objectInputStream;
        Sheep sheep =null;
        try{
            //序例化对象到流
            outputStream=new ByteArrayOutputStream();
            objectOutputStream = new ObjectOutputStream(outputStream);
            objectOutputStream.writeObject(this);
            //从流中读取对象
            inputStream =new ByteArrayInputStream(outputStream.toByteArray());
            objectInputStream = new ObjectInputStream(inputStream);
            sheep = (Sheep) objectInputStream.readObject();

        }catch (Exception ex){

        }
        return sheep;
    }
}
